#!/bin/bash

# Create Release Package Script
# This script creates a release package with binaries, models, and documentation

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"
RELEASE_DIR="${PROJECT_ROOT}/release"
VERSION="${1:-v1.0.0}"
RELEASE_NAME="goyolopenvino-${VERSION}"
RELEASE_PATH="${RELEASE_DIR}/${RELEASE_NAME}"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

echo -e "${GREEN}=== Creating Release Package ===${NC}"
echo "Version: $VERSION"
echo "Release Path: $RELEASE_PATH"
echo ""

# Create release directory structure
echo -e "${YELLOW}Creating directory structure...${NC}"
mkdir -p "$RELEASE_PATH"/{bin,models,config,docs,scripts}

# Copy binaries
echo -e "${YELLOW}Copying binaries...${NC}"
if [ -f "${PROJECT_ROOT}/YOLOv8-OpenVINO-CPP-Inference/bin/detect" ]; then
    cp "${PROJECT_ROOT}/YOLOv8-OpenVINO-CPP-Inference/bin/detect" "$RELEASE_PATH/bin/"
    echo "✓ Copied detect"
else
    echo -e "${RED}✗ detect binary not found${NC}"
fi

if [ -f "${PROJECT_ROOT}/YOLOv8-OpenVINO-CPP-Inference/bin/detect_service" ]; then
    cp "${PROJECT_ROOT}/YOLOv8-OpenVINO-CPP-Inference/bin/detect_service" "$RELEASE_PATH/bin/"
    echo "✓ Copied detect_service"
else
    echo -e "${RED}✗ detect_service binary not found${NC}"
fi

if [ -f "${PROJECT_ROOT}/goyolo/bin/goyolo-service" ]; then
    cp "${PROJECT_ROOT}/goyolo/bin/goyolo-service" "$RELEASE_PATH/bin/"
    echo "✓ Copied goyolo-service"
else
    echo -e "${RED}✗ goyolo-service binary not found${NC}"
fi

# Create models directory with placeholder
echo -e "${YELLOW}Creating models directory...${NC}"
cat > "$RELEASE_PATH/models/README.md" << 'EOF'
# Models Directory

Place your YOLO models here:

## Supported Models
- YOLOv8 (nano, small, medium, large, xlarge)
- YOLOv11 (nano, small, medium, large, xlarge)

## Model Format
- OpenVINO format (.xml + .bin)
- ONNX format (.onnx)

## Example Structure
```
models/
├── yolov8n.xml
├── yolov8n.bin
├── yolov11n.xml
└── yolov11n.bin
```

## Download Models
You can download pre-trained models from:
- https://github.com/ultralytics/yolov8
- https://github.com/ultralytics/yolov11

Or convert them using OpenVINO Model Optimizer:
```bash
mo --input_model model.pt --output_dir models/
```
EOF
echo "✓ Created models directory"

# Create config directory
echo -e "${YELLOW}Creating config directory...${NC}"
cat > "$RELEASE_PATH/config/config.env" << 'EOF'
# Configuration for goyolo-service

# Model Configuration
MODEL_PATH=./models/yolov8n.xml
MODEL_VERSION=YOLOv8
NUM_CLASSES=80

# OpenVINO Configuration
OPENVINO_DEVICE=AUTO
OPENVINO_GPU_STREAMS=1
OPENVINO_NPU_STREAMS=1

# Service Configuration
PORT=8080
HOST=0.0.0.0

# Text Detection Configuration
CONFIDENCE_THRESHOLD=0.5
SAVE_REGIONS=true
OUTPUT_DIR=./output

# C++ Binary Configuration
CPP_BINARY_PATH=./bin/detect_service
EOF
echo "✓ Created config.env"

# Copy documentation
echo -e "${YELLOW}Copying documentation...${NC}"
for doc in BUILD_COMPLETION_REPORT.md REMOTE_BUILD_SUMMARY.md YOLOV11_IMPLEMENTATION.md OPENVINO_INTEGRATION.md; do
    if [ -f "${PROJECT_ROOT}/$doc" ]; then
        cp "${PROJECT_ROOT}/$doc" "$RELEASE_PATH/docs/"
        echo "✓ Copied $doc"
    else
        echo "⚠ Skipped $doc (not found)"
    fi
done

# Create release README
echo -e "${YELLOW}Creating release README...${NC}"
cat > "$RELEASE_PATH/README.md" << 'EOF'
# YOLOv8 OpenVINO Go Service - Release Package

**Version**: v1.0.0  
**Date**: 2025-10-17  
**Status**: Production Ready

## Quick Start

### 1. Extract Release
```bash
tar xzf goyolopenvino-v1.0.0.tar.gz
cd goyolopenvino-v1.0.0
```

### 2. Download Models
```bash
# Download YOLOv8 nano model
wget https://github.com/ultralytics/yolov8/releases/download/v8.0.0/yolov8n.pt
# Convert to OpenVINO format (requires OpenVINO tools)
mo --input_model yolov8n.pt --output_dir models/
```

### 3. Configure
```bash
# Edit configuration
nano config/config.env

# Or use environment variables
export MODEL_PATH=./models/yolov8n.xml
export OPENVINO_DEVICE=AUTO
export PORT=8080
```

### 4. Run Service
```bash
# Set library paths
export LD_LIBRARY_PATH=/opt/intel/openvino_genai_ubuntu24_2025.3.0.0_x86_64/runtime/lib/intel64:$LD_LIBRARY_PATH

# Start service
./bin/goyolo-service
```

### 5. Test API
```bash
# Health check
curl http://localhost:8080/health

# Text detection
curl -X POST http://localhost:8080/api/v1/detect/text \
  -H "Content-Type: application/json" \
  -d '{
    "image_path": "/path/to/image.jpg",
    "output_dir": "./output",
    "confidence_threshold": 0.5,
    "save_regions": true
  }'
```

## Directory Structure

```
goyolopenvino-v1.0.0/
├── bin/                    # Compiled binaries
│   ├── detect             # C++ detection binary
│   ├── detect_service     # C++ service binary
│   └── goyolo-service     # Go service binary
├── models/                # YOLO models (download separately)
│   ├── yolov8n.xml
│   └── yolov8n.bin
├── config/                # Configuration files
│   └── config.env
├── docs/                  # Documentation
│   ├── BUILD_COMPLETION_REPORT.md
│   ├── REMOTE_BUILD_SUMMARY.md
│   ├── YOLOV11_IMPLEMENTATION.md
│   └── OPENVINO_INTEGRATION.md
├── scripts/               # Utility scripts
│   ├── deploy.sh
│   ├── setup.sh
│   └── run.sh
└── README.md             # This file
```

## System Requirements

- **OS**: Ubuntu 20.04+ or similar Linux distribution
- **CPU**: x86_64 processor
- **RAM**: 4GB minimum, 8GB recommended
- **Storage**: 2GB for models and dependencies

## Dependencies

### Required
- OpenVINO Runtime 2025.3.0.0 or later
- OpenCV 4.6.0 or later
- GLIBC 2.31 or later

### Optional
- CUDA 11.0+ (for GPU acceleration)
- Intel GPU drivers (for GPU support)
- NPU drivers (for NPU support)

## Installation

### Option 1: Automated Setup
```bash
chmod +x scripts/setup.sh
./scripts/setup.sh
```

### Option 2: Manual Setup
```bash
# Install OpenVINO
wget https://storage.openvinotoolkit.org/repositories/openvino/packages/2025.3/linux/l_openvino_toolkit_ubuntu24_2025.3.0.0_x86_64.tgz
tar xzf l_openvino_toolkit_ubuntu24_2025.3.0.0_x86_64.tgz
source openvino_genai_ubuntu24_2025.3.0.0_x86_64/setupvars.sh

# Install OpenCV
sudo apt-get install -y libopencv-dev

# Set library paths
export LD_LIBRARY_PATH=/opt/intel/openvino_genai_ubuntu24_2025.3.0.0_x86_64/runtime/lib/intel64:$LD_LIBRARY_PATH
```

## Device Selection

### AUTO (Recommended)
Automatically selects the best available device:
```bash
export OPENVINO_DEVICE=AUTO
```

### GPU
For NVIDIA/Intel GPU acceleration:
```bash
export OPENVINO_DEVICE=GPU
```

### NPU
For Intel Neural Processing Unit:
```bash
export OPENVINO_DEVICE=NPU
```

### CPU
For CPU-only inference:
```bash
export OPENVINO_DEVICE=CPU
```

## Configuration

Edit `config/config.env` to customize:

```bash
# Model settings
MODEL_PATH=./models/yolov8n.xml
MODEL_VERSION=YOLOv8
NUM_CLASSES=80

# Device settings
OPENVINO_DEVICE=AUTO
OPENVINO_GPU_STREAMS=1
OPENVINO_NPU_STREAMS=1

# Service settings
PORT=8080
HOST=0.0.0.0

# Detection settings
CONFIDENCE_THRESHOLD=0.5
SAVE_REGIONS=true
OUTPUT_DIR=./output
```

## API Endpoints

### Health Check
```bash
GET /health
```

### Text Detection
```bash
POST /api/v1/detect/text
Content-Type: application/json

{
  "image_path": "/path/to/image.jpg",
  "output_dir": "./output",
  "confidence_threshold": 0.5,
  "save_regions": true
}
```

## Troubleshooting

### Issue: Library not found
```bash
export LD_LIBRARY_PATH=/opt/intel/openvino_genai_ubuntu24_2025.3.0.0_x86_64/runtime/lib/intel64:$LD_LIBRARY_PATH
```

### Issue: Model not found
```bash
# Check model path
ls -la models/
# Update MODEL_PATH in config/config.env
```

### Issue: Port already in use
```bash
# Use different port
export PORT=8081
```

## Performance Tips

1. **Use AUTO device** for automatic optimization
2. **Adjust stream settings** for your hardware:
   - GPU_STREAMS: 1-4 (higher = more parallelism)
   - NPU_STREAMS: 1-2 (NPU typically supports 1-2)
3. **Batch processing** for multiple images
4. **Use smaller models** (nano/small) for faster inference

## Support

For issues and questions:
- Check documentation in `docs/` directory
- Review build reports in `docs/BUILD_COMPLETION_REPORT.md`
- Check OpenVINO integration guide in `docs/OPENVINO_INTEGRATION.md`

## License

See LICENSE file in the project root.

## Version History

### v1.0.0 (2025-10-17)
- Initial release
- YOLOv8 and YOLOv11 support
- OpenVINO device selection (AUTO, GPU, NPU, CPU)
- Text detection with region cropping
- HTTP REST API
- 50+ unit tests
EOF
echo "✓ Created release README"

# Create deployment scripts
echo -e "${YELLOW}Creating deployment scripts...${NC}"

cat > "$RELEASE_PATH/scripts/setup.sh" << 'EOF'
#!/bin/bash
# Setup script for goyolo-service

set -e

echo "=== Setting up goyolo-service ==="

# Check if running on Linux
if [[ ! "$OSTYPE" == "linux-gnu"* ]]; then
    echo "Error: This script only works on Linux"
    exit 1
fi

# Install dependencies
echo "Installing dependencies..."
sudo apt-get update
sudo apt-get install -y \
    libopencv-dev \
    nlohmann-json3-dev \
    libssl-dev

# Create output directory
mkdir -p output

# Set permissions
chmod +x bin/detect
chmod +x bin/detect_service
chmod +x bin/goyolo-service

echo "✓ Setup complete"
echo ""
echo "Next steps:"
echo "1. Download models: wget https://github.com/ultralytics/yolov8/releases/download/v8.0.0/yolov8n.pt"
echo "2. Convert models: mo --input_model yolov8n.pt --output_dir models/"
echo "3. Configure: nano config/config.env"
echo "4. Run: ./scripts/run.sh"
EOF

cat > "$RELEASE_PATH/scripts/run.sh" << 'EOF'
#!/bin/bash
# Run script for goyolo-service

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RELEASE_DIR="$(dirname "$SCRIPT_DIR")"

# Load configuration
if [ -f "$RELEASE_DIR/config/config.env" ]; then
    export $(cat "$RELEASE_DIR/config/config.env" | grep -v '^#' | xargs)
fi

# Set library paths for OpenVINO
export LD_LIBRARY_PATH=/opt/intel/openvino_genai_ubuntu24_2025.3.0.0_x86_64/runtime/lib/intel64:$LD_LIBRARY_PATH

# Verify binaries exist
if [ ! -f "$RELEASE_DIR/bin/goyolo-service" ]; then
    echo "Error: goyolo-service binary not found"
    exit 1
fi

# Verify model exists
if [ ! -f "$MODEL_PATH" ]; then
    echo "Error: Model not found at $MODEL_PATH"
    echo "Please download and convert models first"
    exit 1
fi

echo "=== Starting goyolo-service ==="
echo "Model: $MODEL_PATH"
echo "Device: $OPENVINO_DEVICE"
echo "Port: $PORT"
echo ""

# Run service
cd "$RELEASE_DIR"
exec ./bin/goyolo-service
EOF

cat > "$RELEASE_PATH/scripts/deploy.sh" << 'EOF'
#!/bin/bash
# Deploy script for production deployment

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
RELEASE_DIR="$(dirname "$SCRIPT_DIR")"
INSTALL_DIR="${1:-/opt/goyolo}"

echo "=== Deploying goyolo-service ==="
echo "Install directory: $INSTALL_DIR"
echo ""

# Create install directory
sudo mkdir -p "$INSTALL_DIR"

# Copy binaries
echo "Copying binaries..."
sudo cp "$RELEASE_DIR/bin/detect" "$INSTALL_DIR/"
sudo cp "$RELEASE_DIR/bin/detect_service" "$INSTALL_DIR/"
sudo cp "$RELEASE_DIR/bin/goyolo-service" "$INSTALL_DIR/"

# Copy configuration
echo "Copying configuration..."
sudo mkdir -p "$INSTALL_DIR/config"
sudo cp "$RELEASE_DIR/config/config.env" "$INSTALL_DIR/config/"

# Create models directory
echo "Creating models directory..."
sudo mkdir -p "$INSTALL_DIR/models"

# Set permissions
echo "Setting permissions..."
sudo chmod +x "$INSTALL_DIR/detect"
sudo chmod +x "$INSTALL_DIR/detect_service"
sudo chmod +x "$INSTALL_DIR/goyolo-service"
sudo chmod 755 "$INSTALL_DIR"

# Create systemd service (optional)
echo "Creating systemd service..."
sudo tee /etc/systemd/system/goyolo.service > /dev/null << SYSTEMD
[Unit]
Description=GoYOLO Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=$INSTALL_DIR
EnvironmentFile=$INSTALL_DIR/config/config.env
ExecStart=$INSTALL_DIR/goyolo-service
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target
SYSTEMD

echo "✓ Deployment complete"
echo ""
echo "To start the service:"
echo "  sudo systemctl start goyolo"
echo "  sudo systemctl enable goyolo"
echo ""
echo "To check status:"
echo "  sudo systemctl status goyolo"
EOF

chmod +x "$RELEASE_PATH/scripts/setup.sh"
chmod +x "$RELEASE_PATH/scripts/run.sh"
chmod +x "$RELEASE_PATH/scripts/deploy.sh"
echo "✓ Created deployment scripts"

# Create archive
echo -e "${YELLOW}Creating archive...${NC}"
cd "$RELEASE_DIR"
tar czf "${RELEASE_NAME}.tar.gz" "$RELEASE_NAME"
echo "✓ Created ${RELEASE_NAME}.tar.gz"

# Create checksum
echo -e "${YELLOW}Creating checksum...${NC}"
sha256sum "${RELEASE_NAME}.tar.gz" > "${RELEASE_NAME}.sha256"
echo "✓ Created ${RELEASE_NAME}.sha256"

# Print summary
echo ""
echo -e "${GREEN}=== Release Package Created ===${NC}"
echo "Location: $RELEASE_DIR"
echo "Archive: ${RELEASE_NAME}.tar.gz"
echo "Size: $(du -h "$RELEASE_DIR/${RELEASE_NAME}.tar.gz" | cut -f1)"
echo ""
echo "Contents:"
echo "  ✓ Binaries (detect, detect_service, goyolo-service)"
echo "  ✓ Configuration (config.env)"
echo "  ✓ Documentation (BUILD_COMPLETION_REPORT.md, etc.)"
echo "  ✓ Scripts (setup.sh, run.sh, deploy.sh)"
echo "  ✓ Models directory (empty, ready for models)"
echo ""
echo "Next steps:"
echo "1. Download models to models/ directory"
echo "2. Extract archive: tar xzf ${RELEASE_NAME}.tar.gz"
echo "3. Run setup: cd ${RELEASE_NAME} && ./scripts/setup.sh"
echo "4. Configure: nano config/config.env"
echo "5. Run: ./scripts/run.sh"

